home *** CD-ROM | disk | FTP | other *** search
- Path: keats.ugrad.cs.ubc.ca!not-for-mail
- From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 22 Jan 1996 09:09:55 -0800
- Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
- Message-ID: <4e0gd3INNa7s@keats.ugrad.cs.ubc.ca>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca> <4dpian$gij@oxy.rust.net> <4drjkc$il4@news.gate.net>
- NNTP-Posting-Host: keats.ugrad.cs.ubc.ca
-
- In article <4drjkc$il4@news.gate.net>, William Hutto <bhutto@gate.net> wrote:
- >In article <4dpian$gij@oxy.rust.net>, ebennett@rust.net spake:
- >;Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
- >;
- >;>Is there a fast way to decide whether a number n is a power of 2?
- >;
- >;
- >;Working with positive numbers, a number will be a power of 2 if there
- >;is exactly one bit set in the number. (For negative numbers, you can
- >;use the following by taking the abs() of the number).
- >
- >Negative numbers? The person in question wasn't asking for a power of -2.
- >Power of 2 has to be > 0 for integers.
- >
- >;
- >;Given some number, there is a neat trick to generate a mask which will
- >;have exactly one bit set in it. The bit set will be the least
- >;significant non-zero bit in the original number:
- >;
- >; mask = ~number & number;
- >
- >It's faster just to use:
- >
- >mask = 0;
- >
- >;
- >;Now, if number contained a single non-zero bit (and is therefore a
- >;power of 2), mask will be equal to number. Therefore:
- >;
- >; if (number == (~number & number))
-
- Umm, the bitwise AND is very much like the AND in truth functional logic.
-
- A statement like "I'm a newbie and I'm not a newbie" is called a contradiction
- because it is always false. Analogously, taking a bitwise complement of a
- number and AND'ing it with the original always produces zero.
-
- A: 0100
- ~A: 1011
- ------------
- A ^ ~A: 0000
-
- --
-
-